package com.alter.auth.manager.impl;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.alter.auth.manager.TokenManager;
import com.alter.auth.model.TokenModel;
import com.alter.config.Constants;


/**
 * @描述: 通过Redis存储和验证token的实现类
 * @作者: alter
 * @时间：2017-8-22 下午10:07:01
 */
@Component
public class RedisTokenManager implements TokenManager {
	/*@Autowired
    private RedisTemplate<Long, String> redis;

    public void setRedis(RedisTemplate redis) {
        this.redis = redis;
        //泛型设置成Long后必须更改对应的序列化方案
        redis.setKeySerializer(new JdkSerializationRedisSerializer());
    }*/
	
	/*@Autowired  
    private RedisTemplate redis;  */
	@Autowired
	private StringRedisTemplate redis;
	
	private static final String USER_SESSION = "user_session";

    public TokenModel createToken(String userId) {
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        TokenModel model = new TokenModel(userId, token);
        //存储到redis并设置过期时间
        //redis.boundValueOps(userId).set(token, Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        redis.boundValueOps(USER_SESSION + ":" + userId).set(JSONObject.toJSONString(model), Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return model;
    }

    public TokenModel getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        String userId = param[0];
        String token = param[1];
        return new TokenModel(userId, token);
    }

    public boolean checkToken(TokenModel model) {
        if (model == null) {
            return false;
        }
        String token = (String) redis.boundValueOps(USER_SESSION + ":" + model.getUserId()).get();
        TokenModel DBmodel = JSONObject.parseObject(token, TokenModel.class);
        if (token == null || !DBmodel.getToken().equals(model.getToken())) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
        redis.boundValueOps(USER_SESSION + ":" + model.getUserId()).expire(Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return true;
    }

    public void deleteToken(String userId) {
        redis.delete(USER_SESSION + ":" + userId);
    }
}